﻿using System;
using System.Drawing;

namespace Fifteen
{
    public class TBitmapSplitter
    {
        private Bitmap bitmap;
        private Bitmap[,] parts;

        public TBitmapSplitter(Bitmap bitmap)
        {
            this.bitmap = bitmap;
        }

        public void Split(int columns, int rows)
        {
            this.parts = new Bitmap[columns, rows];

            Size partSize = new Size(this.bitmap.Size.Width / columns, this.bitmap.Size.Height / rows);
            // TODO: Add adjustment if image cant be divided nicely

            for (int y = 0; y < rows; y++)
            {
                for (int x = 0; x < columns; x++)
                {
                    this.parts[x, y] = new Bitmap(partSize.Width, partSize.Height, this.bitmap.PixelFormat);
                    Graphics g = Graphics.FromImage(this.parts[x, y]);
                    g.DrawImage(this.bitmap, new Rectangle(0, 0, partSize.Width, partSize.Height), new Rectangle(x * partSize.Width, y * partSize.Height, partSize.Width, partSize.Height), GraphicsUnit.Pixel);
                    g.Flush();
                }
            }
        }

        public Bitmap this[int x, int y]
        {
            get
            {
                return this.parts[x, y];
            }
        }

        public Bitmap Original
        {
            get { return this.bitmap; }
        }
    }
}
